package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.domain.User;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        org.springframework.security.core.userdetails.User user =
                (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user != null){
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }
    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<com.itheima.domain.User> list= userService.findAll();
            return  new Result(true,MessageConstant.ADD_MEMBER_FAIL,list);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }

    //根据用户名获取能展示给该用户的菜单
    @RequestMapping("/getMenu")
    public Result getMenu(String username){
        try{
            username = new String(username.getBytes("iso8859-1"),"utf-8");
            List<Map<String,Object>> data = userService.findMenuByUsername(username);
            return new Result(true, MessageConstant.GET_MENU_SUCCESS,data);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MENU_FAIL);
        }
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        try{
            //获取当前登录用户
            org.springframework.security.core.userdetails.User loginUser =
                    (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return userService.findPage(queryPageBean,loginUser.getUsername());
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加用户
     * @param user
     * @param roleIds
     * @return
     */
    @RequestMapping("/add")//二级路径
    public Result add(@RequestBody User user, Integer[] roleIds) {
        try {
            //判断用户数据格式是否正确,双重保险
            if(user != null && user.getUsername() != null && user.getPassword() != null){
                //根据用户名查询数据库是否该用户名已存在
                User target = userService.findByUsername(user.getUsername());
                if(target == null){
                    //用户名不存在
                    //密码加密
                    user.setPassword(passwordEncoder.encode(user.getPassword()));
                    //添加用户
                    userService.add(user, roleIds);
                    //添加成功
                    return new Result(true, MessageConstant.ADD_USER_SUCCESS);
                } else {
                    //用户名存在，添加失败
                    return new Result(false, MessageConstant.ADD_USER_FAIL1);
                }
            } else {
                //添加失败
                return new Result(false, MessageConstant.ADD_FAIL2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //添加失败
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }

    /**
     * 根据id查询
     * @param userId
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer userId) {
        try{
            //判断userId是否为空
            if(userId == null){
                return new Result(false, MessageConstant.QUERY_USER_FAIL1);
            }
            //根据id查询用户
            User user = userService.findById(userId);
            //判断用户是否为空
            if (user != null) {
                //用户不为空,返回查询成功
                return new Result(true, MessageConstant.QUERY_USER_SUCCESS,user);
            } else {
                //该用户不存在
                return new Result(false, MessageConstant.QUERY_USER_FAIL2);
            }
        }catch (Exception e){
            e.printStackTrace();
            //出错，返回查询失败
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 根据用户id查询关联数据的数量
     * @param userId
     * @return
     */
    @RequestMapping("/findCountByUserId")
    public Result findCountByUserId(Integer userId) {
        try{
            //判断userId是否为空
            if(userId == null){
                return new Result(false, MessageConstant.QUERY_USER_FAIL1);
            }
            //根据用户id查询关联数据的数量
            Integer count = userService.findCountByUserId(userId);
            //返回查询成功
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS,count);
        }catch (Exception e){
            e.printStackTrace();
            //出错，返回查询失败
            return new Result(false, MessageConstant.QUERY_COUNT_FAIL);
        }
    }

    /**
     * 根据用户id查询对应的角色id
     * @param userId
     * @return
     */
    @RequestMapping("/findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer userId) {
        try {
            //判断userId是否为空
            if(userId == null){
                return new Result(false, MessageConstant.QUERY_USER_FAIL1);
            }
            //根据用户id查询对应的角色ids
            List<Integer> roleIds = userService.findRoleIdsByUserId(userId);
            //查询成功 将角色ids作为参数返回
            return new Result(true, MessageConstant.QUERY_ROLE_SUCCESS, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            //查询失败,返回失败信息
            return new Result(false, MessageConstant.QUERY_ROLE_FAIL);
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            //判断userId是否为空
            if(id == null){
                return new Result(false, MessageConstant.QUERY_USER_FAIL1);
            }
            //根据用户id查询数据库是否该用户名已存在
            User target = userService.findById(id);
            if(target != null){
                //获取当前登录用户
                org.springframework.security.core.userdetails.User loginUser =
                        (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                //不允许删除自己
                if(loginUser.getUsername().equals(target.getUsername())){
                    //不允许删除自己
                    return new Result(false, MessageConstant.DELETE_USER_FAIL1);
                }
                //根据ID删除
                userService.delete(id);
                //删除成功
                return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
            } else {
                //用户不存在，删除失败
                return new Result(false, MessageConstant.QUERY_USER_FAIL2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //删除失败
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
    }

    /**
     * 修改
     * @param user
     * @param roleIds
     * @return
     */
    @RequestMapping("/edit")
    public Result edit(@RequestBody User user, Integer[] roleIds) {
        try {
            //判断用户数据格式是否正确,双重保险
            if(user != null && user.getUsername() != null && user.getPassword() != null) {
                //获取当前用户名
                org.springframework.security.core.userdetails.User loginUser =
                        (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                //获取数据库中当前用户
                User target = userService.findById(user.getId());
                if(target != null){
                    //获取所有用户排除自己
                    List<User> users = userService.findUsersExOwn(user.getId());
                    //遍历
                    for (User user1 : users) {
                        //判断用户名是否重复
                        if(user1.getUsername().equals(user.getUsername())){
                            //用户名重复
                            return new Result(false,MessageConstant.EDIT_USER_FAIL1);
                        }
                    }
                    //判断密码是否被修改
                    if(!user.getPassword().equals(target.getPassword())){
                        //密码加密
                        user.setPassword(passwordEncoder.encode(user.getPassword()));
                    }
                    //修改用户
                    userService.edit(user,roleIds);
                    //返回修改成功
                    return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
                } else {
                    //该用户不存在
                    return new Result(false, MessageConstant.QUERY_USER_FAIL2);
                }
            }else {
                //编辑格式错误
                return new Result(false, MessageConstant.EDIT_FAIL2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //编辑失败  返回失败信息
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
    }

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        String telephone = (String) map.get("telephone");//从页面获取手机号
        String validateCode = (String) map.get("validateCode");//从页面获取验证码
        String password = (String) map.get("tbPassword");
        //从redis中获取保存的验证
        Jedis resource = jedisPool.getResource();
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_EDITPWD);
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            //验证码输入正确
            //密码加密
            password =passwordEncoder.encode(password);
            //修改密码
            userService.edit2password(password,telephone);
            return new Result(true, MessageConstant.EDIT_MEMBER_PHONE_SUCCESS);
        }else{
            //验证码输入错误
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
